#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc,char* argv[])
{
	if(argc < 2)
	{
		printf("incrrect parameter\n");
		return 1;
	}
	/*
 	 * 1. 创建socket，要创建UDP类型的socket，广播包是用UDP发送的
 	 */
	int client_fd = socket(AF_INET,SOCK_DGRAM,0);
	/*
 	 * 2. 设置socket,ip,port等属性
 	 */
	struct sockaddr_in client_attr;
	client_attr.sin_port = htons((short)atoi(argv[1]));
	client_attr.sin_addr.s_addr = INADDR_ANY;
	client_attr.sin_family = AF_INET;
	
	/*
 	 * 3. 设置 SO_REUSEADDR，避免bind报错
 	 */
	setsockopt(client_fd,SOL_SOCKET,SO_REUSEADDR,(void*)NULL,0);
	/*
 	 * 4. bind绑定ip端口
 	 */
	bind(client_fd,(struct sockaddr*)&client_attr,sizeof(client_attr));

	/*
 	 * 5. 接收广播报数据
 	 */
	struct sockaddr_in server_attr;
	char buf[512] = {'\0'},ip[16] = {'\0'};
	socklen_t addrlen = sizeof(server_attr);
	while(1)
	{
		if(recvfrom(client_fd,buf,sizeof(buf),0,(struct sockaddr*)&server_attr,&addrlen) <= 0)
		{
			perror("recvfrom");
			return 1;
		}
		inet_ntop(AF_INET,&server_attr.sin_addr.s_addr,ip,sizeof(ip));
		printf("server ip : %s;\nbroadcast data : %s\n\n",ip,buf);
	}
	return 0;
}
